/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package demo.controller;

import demo.model.dto.IDataSourceTO;
import demo.model.util.AuthorizePage;
import demo.model.util.Constant;
import demo.model.util.LanguageBundle;
import demo.model.util.SqlBundle;
import demo.model.util.StringUtil;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author tamph
 */
public abstract class WebInit extends HttpServlet {

    protected static IDataSourceTO DB_SETTING;
    protected LanguageBundle LANGUAGE;
    protected static AuthorizePage AUTHORIZE_PAGE;
    protected static SqlBundle SQL_BUNDLE;
    private String lang = Constant.LANG;

    protected void redirect(String path, HttpServletResponse response)
            throws IOException {
        path = "/demo/" + lang + path;
        response.sendRedirect(path);
    }

    protected void forward(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("CONTENT_PAGE_PATH", path);
        request.setAttribute("LANG", lang);
        request.setAttribute("LANGS", Constant.LANGS);
        request.getRequestDispatcher("/template/body.jsp").forward(request, response);
    }


    protected void setTitle(String value, HttpServletRequest request) {
        request.setAttribute("TITLE", value);
    }

    protected void init(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (DB_SETTING == null) {
            DB_SETTING = this.parseContextXML(request);
        }
        
        if (request.getParameter("LANG") != null && StringUtil.isContain(request.getParameter("LANG"), Constant.LANGS)) {
            lang = request.getParameter("LANG");
        } else {
            lang = Constant.LANG;
        }

        LANGUAGE = LanguageBundle.getInstance(lang);

        if (!LANGUAGE.isBuilt()) {
            String absolutePath = getServletContext().getRealPath("/WEB-INF/lang/");
            LANGUAGE.buildPath(absolutePath);
        }

        if (AUTHORIZE_PAGE == null) {
            AUTHORIZE_PAGE = this.parseAuthorizeXML();
        }

        if (!SqlBundle.getInstance().isBuilt()) {
            String absolutePath = getServletContext().getRealPath("/WEB-INF/SQL/");
            SqlBundle.getInstance().buildPath(absolutePath);
            SQL_BUNDLE = SqlBundle.getInstance();
        }
        

    }

    protected Boolean isAuthorize(HttpServletRequest request, HttpServletResponse response) {

        if (AUTHORIZE_PAGE != null) {
            String roleID = "0";
            if (request.getSession().getAttribute("ROLE_ID") != null && !request.getSession().getAttribute("ROLE_ID").toString().equals("")) {
                roleID = request.getSession().getAttribute("ROLE_ID").toString();
            }
            Object[] list = AUTHORIZE_PAGE.get(roleID);
            String pathCurrent = this.getServletName();
            if (list != null) {
                Boolean isAllow = false;
                for (int i = 0; !isAllow && i < list.length; i++) {
                    if (list[i].equals(pathCurrent)) {
                        isAllow = true;
                    }
                }
                return isAllow;
            }
        }
        return false;
    }

    //parse authorize.xml
    private AuthorizePage parseAuthorizeXML() throws ParserConfigurationException, SAXException, IOException {
        AuthorizePage authPage = new AuthorizePage();
        String pathSource = getServletContext().getRealPath("/WEB-INF/authorize.xml");
        DocumentBuilderFactory fap = DocumentBuilderFactory.newInstance();
        DocumentBuilder build = fap.newDocumentBuilder();
        File fi = new File(pathSource);
        Document document = build.parse(fi);
        Element ele = document.getDocumentElement();
        NodeList list = ele.getElementsByTagName("user");
        for (int i = 0; list != null && i < list.getLength(); i++) {
            Node userNode = list.item(i);
            Node roleNode = ((Element) userNode).getElementsByTagName("role_id").item(0);
            Node servletNode = ((Element) userNode).getElementsByTagName("servlet").item(0);
            if (servletNode.getTextContent() != null) {
                String[] servletArray = servletNode.getTextContent().split(",");
                for (int j = 0; servletArray != null && j < servletArray.length; j++) {
                    authPage.add(roleNode.getTextContent(), servletArray[j]);
                }
            }
        }
        return authPage;
    }

    private IDataSourceTO parseContextXML(HttpServletRequest request) throws Exception {
        try {
            DatabaseSourceTO dataSourceTO = new DatabaseSourceTO();
            String pathSource = request.getRealPath(Constant.CONTEXT_XML);
            DocumentBuilderFactory fap = DocumentBuilderFactory.newInstance();
            DocumentBuilder build = fap.newDocumentBuilder();
            File fi = new File(pathSource);
            Document document = build.parse(fi);
            Element ele = document.getDocumentElement();
            NodeList list = ele.getElementsByTagName("datasource");
            if (list.getLength() == 1) {
                Node no = list.item(0);
                NamedNodeMap attributes = no.getAttributes();
                dataSourceTO.setUsername(attributes.getNamedItem("username").getNodeValue());
                dataSourceTO.setPassword(attributes.getNamedItem("password").getNodeValue());
                dataSourceTO.setDriver(attributes.getNamedItem("driver").getNodeValue());
                dataSourceTO.setUrl(attributes.getNamedItem("url").getNodeValue());
                return dataSourceTO;
            } else {
                throw new IndexOutOfBoundsException();
            }
        } catch (Exception ex) {
            throw ex;
        }
    }
    // <editor-fold defaultstate="collapsed" desc="INNER CLASS - DataSourceTO. Click on the + sign on the left to edit the code.">
    private class DatabaseSourceTO implements IDataSourceTO {

        String username;
        String password;
        String url;
        String driver;

        public DatabaseSourceTO() {
            this.url = "";
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getUrl() {
            return this.url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getDriver() {
            return driver;
        }

        public void setDriver(String driver) {
            this.driver = driver;
        }
    }
    // </editor-fold>
}
